package com.hcb.tonguetiphealth.widget.healthShare;

import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.Spanned;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.ScrollView;
import android.widget.TextView;

import com.hcb.tonguetiphealth.adapter.HealthShareCommentListAdapter;
import com.hcb.tonguetiphealth.global.Global;
import com.hcb.tonguetiphealth.manager.JSONManager;
import com.hcb.tonguetiphealth.manager.WeiboManager;
import com.hcb.tonguetiphealth.model.Comment;
import com.hcb.tonguetiphealth.model.HealthShare;
import com.hcb.tonguetiphealth.model.ResDish;
import com.hcb.tonguetiphealth.model.Restaurant;
import com.hcb.tonguetiphealth.model.User;
import com.hcb.tonguetiphealth.util.HttpUtils;
import com.hcb.tonguetiphealth.util.MessageWhat;
import com.hcb.tonguetiphealth.view.MemberHomepageActivity;
import com.hcb.tonguetiphealth.view.R;
import com.hcb.tonguetiphealth.widget.GeneralWidget;

public class HealthShareInfoWidget extends GeneralWidget implements OnClickListener {
	
	private Activity ctx;

	private Handler mHandler;
	private LinearLayout llBack;
	private LinearLayout llCity, llSearch, llHotRes, llLogin, llMore ;
	private User user;
	private List<HealthShare>healthShareList ;
	private ListView healthShareListView;
	private HealthShare healthShare;
	
	private String userName;
	private String count = "0";
	
	private ImageView img, imgUporDown;
	private TextView tvName, tvContent, tvShareNum, tvContentInfo;
	private LinearLayout llContent;
	private Button btHealthShare;
	private RatingBar rb, rbYyjz, rbCpdp, rbLfzs, rbSjhl;
	private int iYyjz, iCpdp, iLfzs, iSjhl;
	private Comment comment;
	private ListView commentListView;
	private List<ResDish> dishList;
	private Restaurant res;
	
	private LinearLayout llProgressBar;
	private ScrollView svContentInfo;
	
	private Spanned sp;
	
	private int type;//type = 1评论提交;=2鲜花加1
	
	private TextView tvFlower;
	private TextView tvShare;
	
	private EditText etComment;
	
	private Button btSubmit;
	
	private List<Comment>commentList = new ArrayList<Comment>();
	
	private Dialog waitDialog;
	
	public HealthShareInfoWidget(Context context) {
		super(context);
		ctx = (Activity)context;
		inflate(context, R.layout.health_share_info, this); 
		
		Bundle bundle = ctx.getIntent().getExtras();
		healthShare = (HealthShare)bundle.get("healthShare");
		sp = Global.sp;
		
		bindView();
		bindEvent();
		getHealthShareCommentList();
	}
	
	private void bindView(){
 
		img = (ImageView)findViewById(R.id.health_share_usr_img);
		imgUporDown = (ImageView)findViewById(R.id.health_share_content_upordown);
		tvName = (TextView)findViewById(R.id.health_name_tv);
		rb = (RatingBar)findViewById(R.id.health_share_ratingbar);
		tvContent = (TextView)findViewById(R.id.health_share_content_textview);
		tvContentInfo = (TextView)findViewById(R.id.health_share_content_info_textview);
		llContent = (LinearLayout)findViewById(R.id.health_share_content_linearout);
		btHealthShare = (Button)findViewById(R.id.health_share_share_button);
		tvFlower = (TextView)findViewById(R.id.health_share_flowernum_textview);
		tvShare = (TextView)findViewById(R.id.health_share_sharenum_textview);
		llProgressBar = (LinearLayout)findViewById(R.id.progressbar_linearlayout);
		commentListView = (ListView)findViewById(R.id.health_share_coment_listview);
		
		svContentInfo = (ScrollView)findViewById(R.id.health_share_scrollview);
		
		etComment = (EditText)findViewById(R.id.health_share_comment_textview);
		btSubmit = (Button)findViewById(R.id.health_share_share_button);
		
		String type = healthShare.getType();
		String contentInfo="";
		if ("1".equals(type)) {
		    res = healthShare.getRes();
			dishList = healthShare.getDishList();	
			for (int i = 0; i < dishList.size(); i++) {
				ResDish dish = dishList.get(i);
				contentInfo += dish.getNum() + "份" +dish.getTitle()+";";
			}
			tvContentInfo.setText(contentInfo);
			String content = "享友在" +res.getName()+ "消费了美食，请您看看是否健康合理";
			tvContent.setText(content);

		}else {
			String content = healthShare.getContent();
			tvContent.setText(content);
		}
		User user = healthShare.getUser();
		tvName.setText(user.getUserName());
		rb.setRating(user.getLevel());
		System.out.println("健康合理指数：" + user.getLevel());
//		tvShareNum.setText("null".equals(user.getCommentNum())?"0":user.getCommentNum());
		tvFlower.setText("null".equals(healthShare.getFlower())?"0": ""+healthShare.getFlower()  );
		tvShare.setText("null".equals(healthShare.getShare())?"0" : ""+ healthShare.getShare() );
		loadImage(img, user.getImgUrl());
		
		llBack = (LinearLayout)findViewById(R.id.healthshare_linearlayout_back);
		
		healthShareListView = (ListView)findViewById(R.id.health_share_listview);
		
	}
	
	private void bindEvent(){
		
		btSubmit.setOnClickListener(this);
		llBack.setOnClickListener(this);
		tvFlower.setOnClickListener(this);
		tvShare.setOnClickListener(this);
		
		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch(msg.what) {
				case MessageWhat.SHOW_DIALOG:
					showMessageDialog(ctx, "正在发送请求...");
					break;
				case MessageWhat.DIMISS_DIALOG:
					dismissMessageDialog();
					if(type == 1){
						showMessage(ctx, "评论成功!");   
						etComment.setText(null);
						commentList.add(0,comment);
						HealthShareCommentListAdapter adapter = new HealthShareCommentListAdapter(ctx, commentList);
						commentListView.setAdapter(adapter);
					}
					else if(type == 2){
						showMessage(ctx, "鲜花+1!");
						healthShare.setFlower(healthShare.getFlower()+1);
						tvFlower.setText( "" + healthShare.getFlower() );
					} else {
						HealthShareCommentListAdapter adapter = new HealthShareCommentListAdapter(ctx, commentList);
						commentListView.setAdapter(adapter);
					}
					break;
				case MessageWhat.SHOW_PROGRESSBAR:
					llProgressBar.setVisibility(View.VISIBLE);
					break;
				case MessageWhat.CLOSE_PROGRESSBAR:
					llProgressBar.setVisibility(View.GONE);
					tvContentInfo.setText(sp);
					svContentInfo.setVisibility(View.VISIBLE);
					break;
				case MessageWhat.NETWORK_FAILD:
					try {
					  dismissMessageDialog();
					} catch (Exception e) {
						// TODO: handle exception
					}
					//Toast.makeText(ctx,  "网络有点不给力哦", Toast.LENGTH_LONG).show();
					showMessage(ctx, R.string.net_faild);
					break;
				}
			}
		};
		
		llContent.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (svContentInfo.getVisibility() == View.GONE || svContentInfo.getVisibility() == View.INVISIBLE) {
					if (sp==null) {
						laodDishPic();
					}else {
						tvContentInfo.setText(sp);
						svContentInfo.setVisibility(View.VISIBLE);
					}
					imgUporDown.setBackgroundResource(R.drawable.close_more);
				}else {
					svContentInfo.setVisibility(View.GONE);
					imgUporDown.setBackgroundResource(R.drawable.open_more); 
				}
			}
		});
		img.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				 Intent intent = new Intent(ctx,MemberHomepageActivity.class);
				 Bundle bundle = new Bundle();
				 bundle.putSerializable("memeber", healthShare.getUser());
				 intent.putExtra("fromWidget", "HealthShareInfoWidget");
				 intent.putExtras(bundle);
				 ctx.startActivity(intent);
			}
		});
	}
	
	
	/**
	 * 底部功能菜单按钮点击事件
	 */
	public void onClick(View v) {
		Intent intent = new Intent();
		switch(v.getId()) {
		//底部按钮
//		case R.id.linearlayout_home_city:
//			break;
//		case R.id.linearlayout_home_search:
//			intent.setClass(ctx, SearchActivity.class);
//			ctx.startActivity(intent);
//			ctx.finish();
//			break;
//		case R.id.linearlayout_home_res:
//			break;
//		case R.id.linearlayout_home_login:
//			intent.setClass(ctx, LoginActivity.class);
//			ctx.startActivity(intent);
//			ctx.finish();
//			break;
//		case R.id.linearlayout_home_more:
//			intent.setClass(ctx, MoreActivity.class);
//			ctx.startActivity(intent);
//			ctx.finish();
//			break;
//			//底部按钮
//		case R.id.home_page_login_login_bt:
//			doLogin();
//			break;
		case R.id.healthshare_linearlayout_back:
			ctx.setContentView(new HealthShareWidget(ctx));
			break;
		case R.id.health_share_share_button:
			if (etComment.getText().toString().trim().equals("")) {
				showMessage(ctx, "评论内容不能为空！");
			}else if(Global.user == null){
				showMessage(ctx, "请登录");
				login();
			}else {
				showLevelDialog();
			}
			break;
		case R.id.health_share_flowernum_textview:
			if(Global.user == null){
				showMessage(ctx, "请登录");
				login();
			} else {
				commitFlower();
			}
			break;
		case R.id.health_share_sharenum_textview:
			WeiboManager weiboManager = new WeiboManager(ctx);
			weiboManager.authWeibo();
			if (weiboManager.isShareSucess()) {
				tvShare.setText(String.valueOf( (healthShare.getShare()+1) ) + "");
			}
			break;
		default:
			break;
		}
	}
	

	/**
	 * 生成html 
	 * @param name
	 * @param picUrl
	 * @return
	 */
	private String namePicUrlToHtml(String title , String picUrl){
		String html= "";
		html += "<br/>" + title  + "<br/>"+
				"&nbsp;&nbsp;&nbsp;&nbsp;" +
				"<img alt=\"\" width=\"675\" height=\"519\" src=" + picUrl+ " /><br/>";
		return html;
	}
	
	private void laodDishPic(){
		
//		//商家名和商家图片 目前是会加载多个其他条目的图片。。。
//		final LinearLayout llLayout = new LinearLayout(view.getContext());
//		final TextView tvResName = new TextView(view.getContext());
//		final ImageView imgRes = new ImageView(view.getContext());
//		llLayout.addView(tvResName, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
//		llLayout.addView(imgRes, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT) );
//		tvResName.setText(res.getName());
//		tvResName.setTextSize(14);
//		loadImg(imgRes, res.getImgURL());
//		llDishPic.addView(llLayout, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		final Message message = new Message();
		message.what = MessageWhat.SHOW_PROGRESSBAR;
//		message.arg1 = position;
		mHandler.sendMessage(message);
		new Thread(){
			@Override
			public void run() {
				// TODO Auto-generated method stub
				String html="";
				if ("1".equals(healthShare.getType())) {
					html += "<br/><span style=\"color: #800000\">"
							+ res.getName() + "<br/>"
							+ "&nbsp;&nbsp;&nbsp;&nbsp;"
							+ "<img alt=\"\" width=\"675\" height=\"519\" src="
							+ res.getImgURL() + " /><br/>";
					//
					for (int i = 0; i < dishList.size(); i++) {
						ResDish dish = dishList.get(i);
						String contentInfo = dish.getNum() + "份"
								+ dish.getTitle() + ":";
						String picUrl = dish.getDishThumb();
						html += namePicUrlToHtml(contentInfo, picUrl);
					}
					html += "<br/></span>";
				}else {
					html += "<br/><span style=\"color: #800000\">"
						+ "&nbsp;&nbsp;&nbsp;&nbsp;"
						+ "<img alt=\"\" width=\"675\" height=\"519\" src="
						+ healthShare.getDiyImg() + " /><br/>";
					html += "<br/></span>";
				}
				
			    sp = Html.fromHtml(html, new Html.ImageGetter() {
					@Override
					public Drawable getDrawable(String source) {
						InputStream is = null;
						try {
							is = (InputStream) new URL(source).getContent();
							Drawable d = Drawable.createFromStream(is, "src");
//							d.setBounds(0, 0, d.getIntrinsicWidth(),
//									d.getIntrinsicHeight());
							d.setBounds(0, 0, 250,//图片宽度、高度设置
									150);
							is.close();
							return d;
						} catch (Exception e) {
							return null;
						}
					}
				}, null);
			    Message message = new Message();
//			    message.arg1 = position;
			    message.what = MessageWhat.CLOSE_PROGRESSBAR;
			    mHandler.sendMessage(message);
			}
			
		}.start();
	}
	 
	private void getHealthShareCommentList(){
		mHandler.sendEmptyMessage(MessageWhat.SHOW_DIALOG);
		healthShareList = new ArrayList<HealthShare>();
		new Thread(){
			public void run() {
				List <NameValuePair> params = new ArrayList <NameValuePair>();
				params.add(new BasicNameValuePair("userId", healthShare.getUser().getUserId()));
				params.add(new BasicNameValuePair("itemoid", healthShare.getContentId()));
				String response = HttpUtils.Post(Global.getServlethealthcomment(), params);
				if (Global.DEBUG) {
					System.out.println("response" + response);
				}
				if (response!=null) {
					parseResponse(response);
					mHandler.sendEmptyMessage(MessageWhat.DIMISS_DIALOG);
				}else {
					mHandler.sendEmptyMessage(MessageWhat.NETWORK_FAILD);
				}
			}
		}.start();
	}
	
	//解析返回的结果（json）
	private void parseResponse(String result){
		JSONManager jsonManager = new JSONManager();
		boolean success = jsonManager.isGotJSONObject(result);
		if (success) {
			JSONArray jsonArray = jsonManager.getJsonList();
			for(int i=0; jsonArray != null  && i < jsonArray.length(); i++) {
				try {
					JSONObject jsonObject = jsonArray.getJSONObject(i);
					Comment comment = new Comment();
					comment.setUser(jsonObject.getString("commenter"));
					comment.setTime(jsonObject.getString("time"));
					comment.setContent(jsonObject.getString("content"));
					comment.setYyjz(jsonObject.getString("yyzs"));
					comment.setLfzs(jsonObject.getString("lfzs"));
					comment.setSjhl(jsonObject.getString("sjhlzs"));
					comment.setCpdp(jsonObject.getString("cpdp"));
					commentList.add(comment);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	protected void showLevelDialog() {
    	waitDialog = new Dialog(ctx, R.style.TRANSDIALOG);
	    waitDialog.setContentView(R.layout.healthshare_ranting_dialog);
	    
	    //设置窗口里控件的透明度
	    Window window = waitDialog.getWindow();
	    WindowManager.LayoutParams wl = window.getAttributes();
	    wl.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
	    wl.alpha = 0.95f;			//０.０全透明．１.０不透明．
	    window.setAttributes(wl);
	    
	    rbYyjz = (RatingBar)waitDialog.findViewById(R.id.health_share_yyjz_ratingbar);
		rbCpdp = (RatingBar)waitDialog.findViewById(R.id.health_share_cpdp_ratingbar);		
		rbLfzs = (RatingBar)waitDialog.findViewById(R.id.health_share_lfzs_ratingbar);		
		rbSjhl = (RatingBar)waitDialog.findViewById(R.id.health_share_sjhl_ratingbar);
	   
    	Button cancel = (Button)waitDialog.findViewById(R.id.health_share_level_cancel_bt);
    	Button skip = (Button)waitDialog.findViewById(R.id.health_share_level_skip_bt);
    	Button ok = (Button)waitDialog.findViewById(R.id.health_share_level_ok_bt);
    	cancel.setOnClickListener(listner);
    	skip.setOnClickListener(listner);
    	ok.setOnClickListener(listner);
    	
    	waitDialog.show();
	}
	OnClickListener listner = new OnClickListener() {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			 iYyjz = (int) rbYyjz.getRating();
			 iCpdp = (int) rbCpdp.getRating();
			 iLfzs = (int) rbLfzs.getRating();
			 iSjhl = (int) rbSjhl.getRating();
			switch(v.getId()) {
			case R.id.health_share_level_cancel_bt:
				break;
			case R.id.health_share_level_skip_bt:
				commit();
				break;
			case R.id.health_share_level_ok_bt:
				comment = new Comment();
				comment.setUser(Global.user.getUserName());
				comment.setContent(etComment.getText().toString());
				comment.setYyjz("" + rbYyjz.getRating());
				comment.setCpdp("" + rbCpdp.getRating());
				comment.setSjhl("" + rbSjhl.getRating());
				comment.setLfzs("" + rbLfzs.getRating());
				commit();
				break;
			}
			waitDialog.dismiss();
		}
	};
	private void commit(){
		mHandler.sendEmptyMessage(MessageWhat.SHOW_DIALOG);
		new Thread(){
			public void run() {
				List <NameValuePair> params = new ArrayList <NameValuePair>();
				params.add(new BasicNameValuePair("userId", healthShare.getUser().getUserId()));
				params.add(new BasicNameValuePair("myUserId", Global.user.getUserId()));
				params.add(new BasicNameValuePair("contentId", healthShare.getItemId()));
				params.add(new BasicNameValuePair("cintent", etComment.getText().toString()));
				params.add(new BasicNameValuePair("yyzs", "" + iYyjz));
				params.add(new BasicNameValuePair("lfzs", "" + iLfzs));
				params.add(new BasicNameValuePair("cpdp", "" + iCpdp));
				params.add(new BasicNameValuePair("sjhl", "" + iSjhl));
				String response = HttpUtils.Post(Global.getServlethealthcommit(), params);
				if (Global.DEBUG) {
					System.out.println("response" + response);
				}
				if (response!=null) {
					try {
						JSONObject jsonObject = new JSONObject(response);
						String strReturn = jsonObject.getString("return");
						if ("true".equals(strReturn)) {
							String time = jsonObject.getString("results");
							comment.setTime(time);
						}else {
							System.out.println("失败");
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					type = 1;
					mHandler.sendEmptyMessage(MessageWhat.DIMISS_DIALOG);
				}else {
					mHandler.sendEmptyMessage(MessageWhat.NETWORK_FAILD);
				}
			}
		}.start();
	}
	
	private void commitFlower(){
		mHandler.sendEmptyMessage(MessageWhat.SHOW_DIALOG);
		new Thread(){
			public void run() {
				List <NameValuePair> params = new ArrayList <NameValuePair>();
				params.add(new BasicNameValuePair("userId", healthShare.getUser().getUserId()));
				params.add(new BasicNameValuePair("myUserId", Global.user.getUserId()));
				System.out.println("--- healthShare.getContentId()"+ healthShare.getContentId());
				params.add(new BasicNameValuePair("contentId", healthShare.getItemId()));
				String response = HttpUtils.Post(Global.getServletflowercommit(), params);
				if (Global.DEBUG) {
					System.out.println("response" + response);
				}
				if (response!=null) {
					try {
						JSONObject jsonObject = new JSONObject(response);
						String strReturn = jsonObject.getString("return");
						if ("true".equals(strReturn)) {
							System.out.println("suncess!!");
							type = 2;
						}else {
							System.out.println("失败");
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					mHandler.sendEmptyMessage(MessageWhat.DIMISS_DIALOG);
				}else {
					mHandler.sendEmptyMessage(MessageWhat.NETWORK_FAILD);
				}
			}
		}.start();
	}
	
	@Override
	public void notifyAdapter() {
		
	}
 
	
}
